package com.common;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @version v1.0.0
 * 创建时间：2022/6/30 15:07
 */
public class TreeNode {

    public int val;
    public TreeNode left;
    public TreeNode right;

    public TreeNode(int x) {
        val = x;
    }

    public TreeNode(int x, TreeNode left, TreeNode right) {
        this.val = x;
        this.left = left;
        this.right = right;
    }

    public static TreeNode buildTree(Integer[] integer) {
        return innerBuildTree(integer);
    }

    private static TreeNode innerBuildTree(Integer[] nodes) {
        if (nodes == null || nodes.length == 0 || nodes[0] == null) return null;
        Deque<TreeNode> queue = new LinkedList<>();
        TreeNode root = new TreeNode(nodes[0]);
        queue.offer(root);
        int index = 1;// 当前根节点的子节点下标
        // 入队非空节点，每个非空节点会让index+2
        while (!queue.isEmpty()) {
            Deque<TreeNode> level = new LinkedList<>();
            while (!queue.isEmpty()) {
                TreeNode node = queue.pop();
                // 当子节点不为空时，连接root和子节点，并且入队。
                if (index < nodes.length && nodes[index] != null) {
                    node.left = new TreeNode(nodes[index]);
                    level.add(node.left);
                }
                index++;
                if (index < nodes.length && nodes[index] != null) {
                    node.right = new TreeNode(nodes[index]);
                    level.add(node.right);
                }
                index++;
            }
            queue = level;
        }
        return root;
    }
}
